<template>
	<view class="container">
		<!-- 顶部轮播图 -->
		<swiper class="swiper" circular :indicator-dots="true" :autoplay="true" :interval="3000" :duration="500">
			<swiper-item v-for="(item, index) in swiperList" :key="index" @click="handleSwiperClick(item)">
				<image :src="item.url" class="swiper-image" />
			</swiper-item>
		</swiper>

		<!-- 模块栏 -->
    <view  :isFull="true">
      <uni-grid :column="5" :showBorder="false" :square="true">
        <uni-grid-item v-for="(item, index) in menuList" :key="index" @click="handleMenuClick(item)">
          <view class="grid-item-box">
            <uni-icons v-if="item.icon" :type="item.icon" size="30"></uni-icons>
            <image v-else class="image" :src="item.image" mode="aspectFill" />
            <text class="text">{{ item.name }}</text>
          </view>
        </uni-grid-item>
      </uni-grid>
    </view>

		<!-- 多功能区域 -->
		<uni-card class="multifunction-area" :class="{ 'plate-mode': cardMode === 1, 'info-mode': cardMode === 2, 'charging-mode': cardMode === 3, 'charge-complete-mode': cardMode === 4 }">

			<!-- 模式1: 车牌输入 -->
			<view v-if="cardMode === 1">
        <view class="card-header">
          <text></text>
          <view class="switch-vehicle" @click="switchMode">
            <uni-icons type="plusempty" size="12"></uni-icons>
            <text>其他车辆</text>
          </view>
        </view>
				<view class="plate-input-wrapper">
					<car-number-input @numberInputResult="numberInputResult" :defaultStr="defaultNum"></car-number-input>
				</view>
				
				
				<!-- 历史车牌 -->
				<view class="history-plates">
					<view class="history-plate-item" v-for="(plate, index) in historyPlates" :key="index">
						<text class="plate-text" @click="queryParkingFee(plate)">{{ plate }}</text>
						<uni-icons type="closeempty" size="16" color="#999" @click="removePlate(index)"></uni-icons>
					</view>
				</view>

				<button class="query-btn" @click="queryParkingFee(null)">查询停车费</button>

			</view>
			<!-- 模式2: 停车信息 -->
			<view v-else-if="cardMode === 2" class="parking-info-content">
				<view class="header">
					<view class="plate-number">
						<text class="plate">{{ parkingInfo.plate }}</text>
						<text class="status">待缴费</text>
					</view>
					<view class="switch-vehicle" @click="switchMode">
						<uni-icons type="plusempty" size="12"></uni-icons>
						<text>其他车辆</text>
					</view>
				</view>
				<view class="details">
					<view class="item">
						<uni-icons type="map-pin-ellipse" size="16"></uni-icons>
						<text>新宇创谷a区地面停车场</text>
					</view>
					<view class="item">
						<uni-icons type="minus" size="16"></uni-icons>
						<text>停车时长：{{ parkingInfo.duration }}</text>
					</view>
					<view class="item">
						<uni-icons type="shop" size="16"></uni-icons>
						<text>缴费金额：{{ parkingInfo.amount }}元</text>
					</view>
					
				</view>
				<button class="pay-btn">立即缴费</button>
			</view>
      <!-- 模式3: 充电中 -->
      <view v-else-if="cardMode === 3" class="charging-content parking-info-content" @click="goToChargingDetail">
        <view class="header">
          <view class="plate-number">
            <text class="plate">{{ chargingInfo.plate }}</text>
            <text class="status charging">充电中</text>
          </view>
        </view>
        <view class="charging-details details">
          <view class="duration-cost-line">
            <text>充电时长: {{ chargingInfo.duration }}</text>
            <text class="billing-info">当前计费: {{ chargingInfo.cost }}元</text>
          </view>
          <view class="progress-bar">
            <progress :percent="chargingInfo.progress" stroke-width="10" activeColor="#2DCC72" border-radius="5"></progress>
            <text>剩余时间: {{ chargingInfo.remainingTime }}</text>
          </view>
          <view class="power-info">
            <text>功率: {{ chargingInfo.power }}kW</text>
            <text>电压: {{ chargingInfo.voltage }}V</text>
            <text>电流: {{ chargingInfo.current }}A</text>
          </view>
        </view>
        <button class="stop-charge-btn" @click.stop="finishCharging">完成充电</button>
      </view>

      <!-- 模式4: 充电完成 -->
      <view v-else-if="cardMode === 4" class="parking-info-content">
        <view class="header">
          <view class="plate-number">
            <text class="plate">{{ chargeCompleteInfo.plate }}</text>
            <text class="status charging">待缴费</text>
          </view>
        </view>
        <view class="details">
          <view class="item">
            <uni-icons type="map-pin-ellipse" size="16"></uni-icons>
            <text>新宇创谷a区充电站</text>
          </view>
          <view class="item">
            <uni-icons type="minus" size="16"></uni-icons>
            <text>充电时长：{{ chargeCompleteInfo.duration }}</text>
          </view>
          <view class="item">
            <uni-icons type="shop" size="16"></uni-icons>
            <text>缴费金额：{{ chargeCompleteInfo.totalCost }}元</text>
          </view>
        </view>
        <button class="stop-charge-btn" @click="payNow">立即缴费</button>
      </view>
		</uni-card>

		<!-- 一键客服 -->
		<view class="customer-service">
			<button class="service-btn" @click="contactService">一键客服</button>
		</view>
		
		<!-- 自定义底部导航栏 -->
		<custom-tabbar :current="currentTabIndex" @change="onTabChange" @centerClick="onCenterClick"></custom-tabbar>
	</view>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { onShow, onLoad } from '@dcloudio/uni-app';
import CarNumberInput from "@/uni_modules/car-number-input/components/car-number-input/car-number-input.vue";
import UniGrid from "@/uni_modules/uni-grid/components/uni-grid/uni-grid.vue";
import UniGridItem from "@/uni_modules/uni-grid/components/uni-grid-item/uni-grid-item.vue";
// import UniIcons from "@/uni_modules/uni-icons/components/uni-icons/uni-icons.vue";
import UniCard from "@/uni_modules/uni-card/components/uni-card/uni-card.vue";
import CustomTabbar from "@/components/custom-tabbar/custom-tabbar.vue";
import { HomeApi } from '@/api/index.js';

// 当前tabbar索引
const currentTabIndex = ref(0);


const swiperList = ref([]);

const defaultNum = ref('');

const cardMode = ref(1); // 1: 输入车牌, 2: 显示停车信息, 3: 充电中, 4: 充电完成

const chargingInfo = ref({
  plate: '皖A12345',
  duration: '1h 25m',
  progress: 75,
  remainingTime: '25m',
  power: 7.2,
  voltage: 220,
  current: 32,
  cost: 18.50
});

const chargeCompleteInfo = ref({
  plate: '皖A12345',
  duration: '1h 50m',
  totalCost: 25.00
});

const parkingInfo = ref({
	plate: '皖A88888',
	entryTime: '2023-10-27 10:00:00',
	duration: '2小时30分钟',
  amount: '15'
});

const  numberInputResult = (e) => {
  console.log('结果--' + e)
  defaultNum.value = e;
}

const queryParkingFee = (plate) => {
  plate = plate ? plate : defaultNum.value.trim();
  console.log(plate);
	if (plate.length === 7 || plate.length === 8) {
		uni.navigateTo({
			url: `/pages/order/index?plate=${plate}`
		});
	} else {
		uni.showToast({
			title: '请输入正确的车牌号',
			icon: 'none'
		});
	}
};

const contactService = () => {
	uni.navigateTo({
		url: '/pages/service/index'
	});
};

// 模拟检查停车状态
const checkParkingStatus = () => {
	// 在这里调用后端接口检查车辆是否在场
	// 此处用一个随机数模拟
	// const inParking = Math.random() > 0.5;
	// if (inParking) {
	// 	cardMode.value = 2;
	// 	console.log('车辆在场，切换到模式2');
	// } else {
	// 	cardMode.value = 1;
	// 	console.log('车辆不在场，切换到模式1');
	// }
};

onLoad((options) => {
  if (options.cardMode) {
    const mode = parseInt(options.cardMode, 10);
    if (!isNaN(mode) && [1, 2, 3, 4].includes(mode)) {
      cardMode.value = mode;
    }
  }
});

onMounted(() => {
	// 页面加载时获取轮播图数据
	loadBanners();
});

onShow(() => {
	// 设置当前tabbar索引
	currentTabIndex.value = 0;
	checkParkingStatus();
});

const switchMode = () => {
	// 实际场景中，这里会弹出选择历史车辆或绑定车辆的列表
	// 这里我们只在模式1和模式2之间切换
	cardMode.value = cardMode.value % 4 + 1; // Cycle through modes 1, 2, 3, 4
};

const finishCharging = () => {
  // 实际应用中会调用API停止充电
  console.log('完成充电');
  cardMode.value = 4; // 切换到充电完成界面
};

const goToChargingDetail = () => {
  // 跳转到充电详情页
  uni.navigateTo({
    url: '/pages/charge/detail'
  });
};

const payNow = () => {
  // 跳转到支付页面
  console.log('立即缴费');
  uni.navigateTo({ url: '/pages/payment/index' });
};

const historyPlates = ref(['皖A88888', '皖B99999', '皖C12345D']);

const removePlate = (index) => {
	historyPlates.value.splice(index, 1);
};

const handleMenuClick = (item) => {
	switch (item.name) {
		case '扫码':
			scanCode()
			break;
		case '找停车':
			uni.switchTab({ url: '/pages/list/list?type=parking' });
			break;
		case '找充电':
			uni.switchTab({ url: '/pages/list/list?type=charging' });
			break;
		case '绑定车辆':
			uni.navigateTo({ url: '/pages/vehicle/bind' });
			break;
		case '充值':
			uni.navigateTo({ url: '/pages/recharge/index' });
			break;
		case '停车卡':
			uni.navigateTo({ url: '/pages/parking-card/index' });
			break;
		case '发票':
			uni.navigateTo({ url: '/pages/invoice/list' });
			break;
		case '账单':
      uni.navigateTo({ url: '/pages/order/list' });
      break;
    case '共享充电桩':
      uni.navigateTo({ url: '/pages/activity/shared-pile/index' });
      break;
			case '更多':
			default:
				uni.showToast({ title: '功能开发中', icon: 'none' });
				break;
	}
};

const scanCode = () => {
	console.log("调用扫码")
	uni.scanCode({
				onlyFromCamera: true,
				success: function (res) {
					uni.showToast({
						title: '扫描内容：' + res.result
					});
				}
			});
};

const handleSwiperClick = (item) => {
	// 根据API返回的clickModel判断是否需要跳转
	if (item.clickModel === 1 && item.jumpLink) {
		// 判断是内部页面还是外部链接
		if (item.jumpLink.startsWith('http')) {
			// 外部链接
			uni.openURL({ url: item.jumpLink });
		} else {
			// 内部页面
			uni.navigateTo({ url: item.jumpLink });
		}
	}
};

// 获取轮播图数据
const loadBanners = async () => {
	try {
		const data = await HomeApi.getBanners();
			// 将API返回的数据格式转换为组件需要的格式
			swiperList.value = data.map(item => ({
				url: item.image,
				jumpLink: item.jumpLink,
				clickModel: item.clickModel
			}));
	} catch (error) {
		console.error('获取轮播图数据失败:', error);
		// 如果接口调用失败，可以设置默认数据
		// swiperList.value = [
		// 	{ url: '/static/logo.png', jumpLink: '/pages/activity/index', clickModel: 1 }
		// ];
	}
};

const menuList = ref([
	{ name: '扫码', image: 'https://tg-spcs.oss-cn-hangzhou.aliyuncs.com/static/logo.png' , icon: 'scan'},
	{ name: '找停车', image: 'https://tg-spcs.oss-cn-hangzhou.aliyuncs.com/static/logo.png',icon: 'map-pin-ellipse'},
	{ name: '找充电', image: 'https://tg-spcs.oss-cn-hangzhou.aliyuncs.com/static/logo.png', icon: 'link' },
	{ name: '绑定车辆', image: 'https://tg-spcs.oss-cn-hangzhou.aliyuncs.com/static/logo.png', icon: 'cart' },
	{ name: '充值', image: 'https://tg-spcs.oss-cn-hangzhou.aliyuncs.com/static/logo.png', icon: 'shop' },
	{name: '停车卡', image: 'https://tg-spcs.oss-cn-hangzhou.aliyuncs.com/static/logo.png', icon: 'vip'},
	{name: '发票', image: 'https://tg-spcs.oss-cn-hangzhou.aliyuncs.com/static/logo.png', icon: 'paperclip'},
	{name: '账单', image: 'https://tg-spcs.oss-cn-hangzhou.aliyuncs.com/static/logo.png', icon: 'calendar'},
  {name: '共享充电桩', image: 'https://tg-spcs.oss-cn-hangzhou.aliyuncs.com/static/logo.png', icon: 'paperplane'},
]);

// 处理底部导航栏切换
const onTabChange = (index) => {
	// console.log('切换到tab:', index);
	
};

// 处理中间按钮点击
const onCenterClick = () => {
	console.log('点击中间按钮');
	// 可以调用扫码功能
	scanCode();
};

</script>

<style scoped>

.grid-item-box {
	flex: 1;
	/* #ifndef APP-NVUE */
	display: flex;
	/* #endif */
	flex-direction: column;
	align-items: center;
	justify-content: center;
	padding: 5px 0;
}

.image {
	width: 50rpx;
	height: 50rpx;
}

.text {
	font-size: 24rpx;
	margin-top: 5rpx;
}

.customer-service {
	position: fixed;
	bottom: 200rpx;
	left: 20rpx;
	right: 20rpx;
	z-index: 100;
}

/* 为页面内容添加底部间距，避免被导航栏遮挡 */
.container {
	padding-bottom: 160rpx;
}

.service-btn {
	background-color: #fff;
	color: #12ada9;
	border: 1px solid #1DCFB7;
	border-radius: 5rpx;
	border-radius: 1.5625rem;
	width: 80%;
}

.plate-input-wrapper {
	margin-bottom: 20rpx;
}

.history-plates {
	display: flex;
	flex-wrap: wrap;
	margin-bottom: 20rpx;
}

.history-plate-item {
	display: flex;
	align-items: center;
	background-color: #f0f0f0;
	padding: 5rpx 10rpx;
	border-radius: 5rpx;
	margin-right: 10rpx;
	margin-bottom: 10rpx;
	font-size: 24rpx;
	border-radius: 0.3rem;

}

.plate-text {
	margin-right: 5rpx;
}

.query-btn {
	background:  linear-gradient(135deg, #1DCFB7, #12ada9 100%);
	color: #fff;
	border-radius: 1.0625rem;
	width: 80%;

}

.parking-info-content {
	/* 模式2的样式 */
}

.parking-info-content .header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 20rpx;
}

.parking-info-content .plate-number {
	display: flex;
	align-items: center;
}

.parking-info-content .plate {
	font-size: 32rpx;
	font-weight: bold;
	margin-right: 10rpx;
}

.parking-info-content .status {
	background-color: #ff9800;
	color: #fff;
	padding: 2rpx 8rpx;
	border-radius: 5rpx;
	font-size: 20rpx;
}

.switch-vehicle {
	display: flex;
	align-items: center;
	color: #007aff;
	font-size: 24rpx;
}

.parking-info-content .details {
	/* display: flex; */
	/* justify-content: space-between; */
}

.parking-info-content .details .item {
	display: flex;
	align-items: center;
	font-size: 24rpx;
	margin-bottom: 10rpx;
}

.parking-info-content .details .item uni-icons {
	margin-right: 10rpx;
}

.pay-btn {
	background-color: #ff9800;
	color: #fff;
	margin-top: 20rpx;
	border-radius: 1.5625rem;
}

.container {
	/*padding: 20rpx;*/
	background-color: #ffffff;
}

.swiper {
	height: 380rpx;
	/*margin-bottom: 20rpx;*/
}

.swiper-image {
	width: 100%;
	height: 100%;
	border-radius: 10rpx;
}

.multifunction-area {
	/*margin: 20rpx 0 !important;*/
	background-color: #e6f7ff;
	border: 1px solid #91d5ff;
}

.multifunction-area.plate-mode {
  background-color: #fffbe6;
  border: 1px solid #91d5ff;
  background-image: linear-gradient(#50fffa69, #ffffff 30%, #ffffff);
}

.multifunction-area.info-mode {
	background-color: #fffbe6;
	border: 1px solid #ffe58f;
  background-image: linear-gradient(#ffe58f9c, #ffffff 30%, #ffffff);

}

.multifunction-area.charging-mode,
.multifunction-area.charge-complete-mode {
  background-color: #e9f9f0;
  border: 1px solid #2DCC72;
  background-image: linear-gradient(rgba(45, 204, 114, 0.2), #ffffff 30%, #ffffff);
}

.status.charging {
  background-color: #e9f9f0;
  color: #2DCC72;
  border: 1px solid #2DCC72;
}

.duration-cost-line {
  display: flex;
  justify-content: space-between;
  width: 100%;
}

.billing-info {
  text-align: right;
}

.charging-details {
  display: flex;
  flex-direction: column;
  gap: 10px;
  margin-bottom: 10px;
}
.charge-summary {
  display: flex;
  flex-direction: column;
  gap: 10px;
  margin-bottom: 20px;
}

.progress-bar {
  display: flex;
  align-items: center;
  gap: 10px;
}

.progress-bar progress {
  flex: 1;
}

.power-info {
  display: flex;
  justify-content: space-around;
}

.stop-charge-btn, .pay-now-btn {
  background-color: #2DCC72;
  color: white;
  border-radius: 20px;
}

.card-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 20rpx;
}

.switch-btn {
	color: #007aff;
	font-size: 24rpx;
	border-radius: 1.5625rem;
}
</style>
